// pages/wholeHouse/wholeHouse.js
const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
var qqmapsdk

var leftHeight = 0
var rightHeight = 0 //分别定义左右两边的高度
var query = null
// let leftHeight = 0,
//   rightHeight = 0; //分别定义左右两边的高度
// let query;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: '', // 搜索内容
    // 瀑布流
    // 瀑布流
    list: [],
    leftList: [],
    rightList: [],

    // 服务类型
    queryParentList: [],
    sys_attribute: [], //瞬间类别字典
    active: 0, //tab切换
    clickItem: null, //当前点击的字典
    pageSize: 6,
    pageNum: 1,

    // 地理位置
    province: '',
    city: '',
    latitude: '',
    longitude: '',
    chooseCity: null,
  },

  // 搜索
  searchOnChange(e) {
    this.setData({
      value: '',
    });
  },
  onSearch() {

  },
  searchOnClick() {

  },
  // tab  切换
  onChangetab(event) {
    // console.log(event.detail.name);
    var index = +event.detail.name
    var data = this.data.sys_attribute[index]
    this.setData({
      list: [],
      leftList: [],
      rightList: [],
      pageSize: 8,
      pageNum: 1,
      clickItem: data
    })
    // console.log(leftHeight, leftHeight);
    // console.log(event.detail.name);
    // console.log(index);

    this.getMomentList(data)
  },


  // 瀑布流
  async isLeft() {
    const {
      list,
      leftList,
      rightList
    } = this.data;
    query = wx.createSelectorQuery();
    for (const item of list) {
      leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
      await this.getBoxHeight(leftList, rightList);
    }
  },
  getBoxHeight(leftList, rightList) { //获取左右两边高度
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      }, () => {
        query.select('#left').boundingClientRect();
        query.select('#right').boundingClientRect();
        query.exec((res) => {
          leftHeight = res[0].height; //获取左边列表的高度
          rightHeight = res[1].height; //获取右边列表的高度
          resolve();
        });
      });
    })
  },



  //跳转
  navigateTo(e) {
    const data = e.currentTarget.dataset.data //跳转参数
    const path = e.currentTarget.dataset.path

    wx.navigateTo({
      url: path,
    })
  },
  navigateToDetail(e) {
    const momentId = e.currentTarget.dataset.momentid //跳转参数
    const path = e.currentTarget.dataset.path
    // console.log(path + "?momentId=" + momentId);

    wx.navigateTo({
      url: `${path}?momentId=${momentId}`
    })
  },
  //获取瞬间列表  manage/mobileUser/moment/list
  getMomentList(data) {
    console.log(data);
    wx.showLoading({
      title: '加载中...',
      success: () => {}
    })



    var postObj = {
      url: '/mobileUser/moment/list',
      method: 'get',
      data: {
        momentAttr: data.dictValue,
        pageSize: this.data.pageSize,
        pageNum: this.data.pageNum,
      }
    }
    app.request.loginRequest(postObj).then(res => {
      if (res.data.code === 200) {
        wx.hideLoading({
          complete: (res) => {},
        })
        // console.log('获取瞬间列表', res);
        var rows = res.data.rows

        if (rows.length > 0) {
          rows.forEach((items, i) => {
            items.sysUser.avatar = app.util.config().api + items.sysUser.avatar
            if (items.sysMomentFile.length > 0) {
              items.sysMomentFile.forEach((items1, i) => {
                items1.url = app.util.config().api + items1.url
              })
            }
          })
        }
        var list = [...this.data.list, ...rows]

        this.setData({
          list: list
        })
        // console.log('获取瞬间列表', this.data.list);

        if (rows.length > 0) {
          this.isLeft()
        }
      }
    })
  },
  // 获取服务类型  http://localhost:8082/manage/mobileUser/apply/queryParentList
  queryParentList() {
    var postObj = {
      url: '/mobileUser/apply/queryParentList',
      method: 'get'
    }
    app.request.loginRequest(postObj).then(res => {
      if (res.data.code === 200) {
        res.data.data.forEach((items, i) => {
          items.typeUrl = app.util.config().api + items.typeUrl
        })
        this.setData({
          queryParentList: res.data.data
        })
        // console.log('获取服务类型', this.data.queryParentList);

      }
    })
  },
  // 聚焦跳转  bind:focus='focusSearch'
  focusSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this

    // 获取服务类型
    that.queryParentList()

    //获取瞬间类别字典  sys_attribute
    app.getDict('sys_attribute').then(res => {
      let sys_attribute = res.data.data
      // console.log('获取瞬间类别字典', sys_attribute);
      that.setData({
        sys_attribute: sys_attribute,
        clickItem: sys_attribute[0]
      })
      that.getMomentList(sys_attribute[0])
      // that.isLeft();
    })

    // that.isLeft();
    qqmapsdk = new QQMapWX({
      key: app.util.config().key //这里自己的key秘钥进行填充
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    // 获取在线地理位置
    that.getUserLocation();
    //获取本地存储地址
    var chooseCity = !!wx.getStorageSync('chooseCity') ? JSON.parse(wx.getStorageSync('chooseCity')).cityName : ''
    that.setData({
      chooseCity: chooseCity
    })
  },
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res);

        // console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude
        })

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this

    that.setData({
      pageSize: 8,
      pageNum: that.data.pageNum + 1,
    })
    that.getMomentList(that.data.clickItem)

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})